/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.device.server.listener;

import com.bugull.farm.core.cache.PropertiesCache;
import com.bugull.farm.core.utils.ByteUtil;
import com.bugull.farm.device.server.cache.DeviceCache;
import com.bugull.redis.listener.TopicListener;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelId;

import org.apache.logging.log4j.*;

import java.util.Arrays;

/**
 * control request from app. just write to the channel.
 * 
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class DeviceTopicListener extends TopicListener {
    private static Logger logger = LogManager.getLogger(DeviceTopicListener.class);
    @Override
    public void onTopicMessage(String topic, byte[] msg) {
    	logger.debug("receivce from topic : "+topic+"[ "+ByteUtil.toHexString(msg)+" ]");
        if(!topic.equals(PropertiesCache.getInstance().get("redis.topic.app"))){
            return;
        }
        byte[] mac = Arrays.copyOfRange(msg, 2, 8);
        String macString = ByteUtil.toHexString(mac);
        DeviceCache cache = DeviceCache.getInstance();
        ChannelId channelId = cache.getChannelId(macString);
        //channelId is not null only on 1 out of N server 
        if(channelId != null){
        	Channel channel = cache.getChannel(channelId);
        	if(channel != null){
        		ByteBuf buf = Unpooled.buffer();
                buf.writeBytes(msg);
                channel.writeAndFlush(buf);
        	}
        }
    }

}
